<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/29
 * Time: 11:22
 */

namespace app\api\controller\v1;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;
use app\api\service\Token;
use app\api\model\User as UserModel;

class Address extends BaseController
{
    //前置操作
    protected $beforeActionList = [
        'needPrimaryScope' => ['only' => 'createOrUpdateAddress'],
    ];
    //地址保存方法
    public function createOrUpdateAddress()
    {
        $addressData = Input('post.');
        $validate = Validate('Address') -> check($addressData);
        if(!$validate) return Validate('Address') -> getError();
        //用自定义的验证器过滤掉违法字段
        $addressData = Validate('Address') -> getDataByRule($addressData);
        $uid = Token::getCurrentUid();
        $user = UserModel::get($uid);
        if(!$user) throw new UserException();
        $address = $user -> address;
        if(!$address) {
            $user -> address() -> save($addressData);
        }else {
            $user -> address -> save($addressData);
        }
        return json(new SuccessMessage(), 201);
    }
}